package UDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

//实现一个UDP客户端，用于向服务器发送消息并接收服务器的响应。
public class EchoClient {
    //创建一个DatagramSocket对象，用于发送和接收数据报。
    private DatagramSocket clientSocket;
    //服务器的IP地址。
    private String serverIp;
    //服务器的端口号。
    private int serverPort;

    //构造方法
    public EchoClient(String serverIp, int serverPort) throws Exception {
        clientSocket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    //启动客户端
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端已启动...");
        while (true) {
            // 1. 从控制台读取用户输入的请求内容
            System.out.print("> ");
            String request = scanner.next();
            // 2. 把请求内容封装成 DatagramPacket 对象
            //    不但要填写数据，还要填写服务器的 IP 地址和端口号
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length, InetAddress.getByName(serverIp), serverPort);
            // 3. 发送请求到服务器
            clientSocket.send(requestPacket);
            System.out.println("客户端已发送请求：" + request);

            
            // 4. 读取服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            clientSocket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println("得到服务器响应：" + response);
        }
    }

    public static void main(String[] args) throws Exception {
        EchoClient client = new EchoClient("127.0.0.1", 9090);
        client.start();
    }

}
